package service

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"lot_admin_api/internal/consts"
	"lot_admin_api/internal/dao"
	"lot_admin_api/internal/model"
	"lot_admin_api/utility/paging"
	"lot_admin_api/utility/response"
)

type sOrder struct{}

var (
	insOrder = sOrder{}
)

func Order() *sOrder {
	return &insOrder
}

// OrderList 获取订单列表
func (s *sOrder) OrderList(ctx context.Context, req *model.OrderSearchList) (res *model.OrderListRes, err error) {
	r := g.RequestFromCtx(ctx)
	startNum, endNum := paging.Paging(req.Paging)
	orderList := make([]*model.OrderInfoDbRes, 0)
	var countInfo int
	searchList := g.Map{
		"charging_mode": req.ChargingMode,
		"end_reason":    req.EndReason,
		"user_id":       req.UserId,
	}
	daoSql := dao.LotOrder.Ctx(ctx).OmitEmpty().WithAll().Where(searchList).Limit(startNum, endNum).OrderDesc("updated_at")
	searchDaoSql := daoSql
	//未完成
	if req.Status == 1 {
		searchDaoSql = searchDaoSql.WhereNull("end_time")
	}
	// 已完成
	if req.Status == 2 {
		searchDaoSql = searchDaoSql.WhereNotNull("end_time")
	}
	if err = searchDaoSql.Scan(&orderList); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	// 获取总条数
	countInfo, err = searchDaoSql.Count()
	putCount := paging.PutCount(req.Paging, countInfo)
	res = &model.OrderListRes{
		List:    orderList,
		PutPage: putCount,
	}
	return res, err
}

// OrderInfo 获取订单详情
func (s *sOrder) OrderInfo(ctx context.Context, req *model.OrderIdRes) (res *model.OrderDetailsDbRes, err error) {
	r := g.RequestFromCtx(ctx)
	if err = dao.LotOrder.Ctx(ctx).WithAll().Where("id", req.Id).Scan(&res); err != nil {
		response.JsonExit(r, consts.HTTPInternalServer.Code(), err.Error())
	}
	return res, err
}
